package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        ////调用阿里云提供的短信服务API完成发送短信
        //SMSUtils.sendMessage("传智健康", "code_1234", phone, code);
        log.info("code={}", code);

        //需要将生成的验证码保存到Session
        request.getSession().setAttribute(phone, code);
        return R.success("手机验证码短信发送成功");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        String code1 = map.get("code");
        //从Session中获取保存的验证码
        String code2 = (String) request.getSession().getAttribute(phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (!StringUtils.equals(code1, code2)) {
            return R.error("验证码错误");
        }

        //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            //新用户注册
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            userService.save(user);
        }
        //将用户存入session中
        request.getSession().setAttribute("user", user.getId());
        return R.success(user);
    }
}
